package com.hd.platform.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

public class ImageTools {
	
	/**
	 * 创建缩略图
	 * @param data
	 * @param newFile
	 * @param ext       ext是图片的格式 gif JPG 或png
	 * @param sizeH     图高
	 * @param sizeW     图宽
	 * @return
	 */
	public static void CreateThumbnail(final byte[] data, String newFile,
			String ext, double sizeH, double sizeW) throws IOException{
		double RatioH = 0.0;
		double ratioW = 0.0;
		File fNew = new File(newFile);
		BufferedImage bi = ImageIO.read(new ByteArrayInputStream(data));
		//假设图片宽 高 最大为16 16
		Image Itemp = bi.getScaledInstance((int) sizeW, (int) sizeH, bi.SCALE_SMOOTH);
		//RatioH = sizeH / bi.getHeight();
		//ratioW = sizeW / bi.getWidth();
		RatioH = 0.5;
		ratioW = 0.5;
		AffineTransformOp op = new AffineTransformOp(AffineTransform
				.getScaleInstance(ratioW, RatioH), null);
		Itemp = op.filter(bi, null);
		ImageIO.write((BufferedImage) Itemp, ext, fNew);
	}

	/**
	 * 创建缩略图
	 * @param data
	 * @param sizeH     图高
	 * @param sizeW     图宽
	 * @return data[]
	 */
	public static byte[] CreateThumbnailBuffer(final byte[] data,  double sizeH, double sizeW,String ext) throws IOException{
		double RatioH = 0.0;
		double ratioW = 0.0;
		BufferedImage bi = ImageIO.read(new ByteArrayInputStream(data));
		//假设图片宽 高 最大为16 16
		Image Itemp = bi.getScaledInstance((int) sizeW, (int) sizeH, bi.SCALE_SMOOTH);
		RatioH = sizeH / bi.getHeight();
		ratioW = sizeW / bi.getWidth();
		AffineTransformOp op = new AffineTransformOp(AffineTransform
				.getScaleInstance(ratioW, RatioH), null);
		Itemp = op.filter(bi, null);
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageOutputStream  output =  ImageIO.createImageOutputStream(baos);
		ImageIO.write((BufferedImage) Itemp, ext, output);
		return baos.toByteArray();
	}
	
	public static boolean cutImage(String oldFile, String newFile,
			String ext,int topLeftX, int topLeftY, int sizeH, int sizeW)
	{
		 	Image img;   
	        ImageFilter cropFilter;   
	        // 读取源图像   
	        BufferedImage src;
			try {
				src = ImageIO.read(new File(oldFile));
			} catch (IOException e) {
				return false;
			}   

            cropFilter = new CropImageFilter(topLeftX, topLeftY, sizeW, sizeH);   
            img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(src.getSource(), cropFilter));   
            BufferedImage tag = new BufferedImage(sizeW, sizeH, BufferedImage.TYPE_INT_RGB);   
            
            Graphics g = tag.getGraphics();   
            g.drawImage(img, 0, 0, null); // 绘制小图   
            g.dispose(); 
            
            // 输出为文件   
            File f = new File(newFile);   
            try {
				ImageIO.write(tag,ext, f);
				return true;
			} catch (IOException e) {
				return false;
			}   

	}
	 
	/**
	 * 文字水印  主要用来处理徽章
	 * @param pressText
	 * @param srcImg
	 * @param targetImg
	 * @param fontName
	 * @param fontStyle
	 * @param color
	 * @param fontSize
	 * @param x
	 * @param y
	 * @param alpha
	 */
	public static void pressText(String[] pressText, String srcImg, String targetImg, String[] fontName, Integer[] fontStyle, Color[] color, Integer[] fontSize, Integer[] x, Integer[] y, float alpha) {  
	    try {  
		    	File img = new File(targetImg);  
		        Image src = ImageIO.read(new File(srcImg));  
		        int width = src.getWidth(null);  
		        int height = src.getHeight(null);  
		        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
		        Graphics2D g = image.createGraphics();  
		        
		     // ----------  增加下面的代码使得背景透明  -----------------
		        image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
		        g.dispose();
		        g = image.createGraphics();
		        // ----------  背景透明代码结束  -----------------
		        g.drawImage(src, 0, 0, width, height, null);  
		        
		        for (int i = 0; i < pressText.length; i++) {
		        	g.setColor(color[i]);  
		        	g.setFont(new Font(fontName[i], fontStyle[i], fontSize[i]));  
		        	g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));  
		        	g.drawString(pressText[i], (width - (getLength(pressText[i]) * fontSize[i])) / 2 + x[i], (height - fontSize[i]) / 2 + y[i]);  
		        	//g.drawString(pressText, x, y+fontSize);  
				}
		        g.dispose();  
		        ImageIO.write((BufferedImage) image, "png", img);  
	        } catch (Exception e) {  
	        	
	        }  
	  }  
	  
	    public final static void pressImage(String pressImg, String targetImg, int x, int y, float alpha) {  
	        try {  
	            File img = new File(targetImg);  
	            Image src = ImageIO.read(img);  
	            int wideth = src.getWidth(null);  
	            int height = src.getHeight(null);  
	            BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);  
	            Graphics2D g = image.createGraphics();  
	            g.drawImage(src, 0, 0, wideth, height, null);  
	            //水印文件  
		        Image src_biao = ImageIO.read(new File(pressImg));  
		        int wideth_biao = src_biao.getWidth(null);  
		        int height_biao = src_biao.getHeight(null);  
		        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));  
		        g.drawImage(src_biao, (wideth - wideth_biao) / 2, (height - height_biao) / 2, wideth_biao, height_biao, null);  
		        //水印文件结束  
		        g.dispose();  
		        ImageIO.write((BufferedImage) image, "jpg", img);  
		        } catch (Exception e) {  

		        }  
	    }  
	 
	  
	    public static void resize(String filePath, int height, int width, boolean bb) {  
	    	try {  
		            double ratio = 0.0; //缩放比例   
			        File f = new File(filePath);  
			        BufferedImage bi = ImageIO.read(f);  
			        Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);  
			        //计算比例  
			        if ((bi.getHeight() > height) || (bi.getWidth() > width)) {  
			            if (bi.getHeight() > bi.getWidth()) {  
			                ratio = (new Integer(height)).doubleValue() / bi.getHeight();  
			            } else {  
			                ratio = (new Integer(width)).doubleValue() / bi.getWidth();  
			            }  
			            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);  
			            itemp = op.filter(bi, null);  
			        }  
			        if (bb) {  
			            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
			            Graphics2D g = image.createGraphics();  
			            g.setColor(Color.white);  
			            g.fillRect(0, 0, width, height);  
			            if (width == itemp.getWidth(null))  
			                g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);  
			            else 
			                g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);  
			            g.dispose();  
			            itemp = image;  
			        }  
			        ImageIO.write((BufferedImage) itemp, "jpg", f);  
		    } catch (IOException e) {  

		    }  
	    }  
		
	    public static void resize(final byte[] data, File f) {  
	    	try {
			        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(data));
			        Image itemp = bi.getScaledInstance(bi.getWidth(), bi.getHeight(), bi.SCALE_DEFAULT);
			        
			        BufferedImage image = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB);  
		            Graphics2D g = image.createGraphics();  
		            g.setColor(Color.white);  
		            g.fillRect(0, 0, bi.getWidth(), bi.getHeight());  
		            if (bi.getWidth() == itemp.getWidth(null))  
		                g.drawImage(itemp, 0, (bi.getHeight() - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);  
		            else 
		                g.drawImage(itemp, (bi.getWidth() - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);  
		            g.dispose();  
		            itemp = image; 
			        
			        ImageIO.write((BufferedImage) itemp, "jpg", f);
		    } catch (IOException e) {  

		    }  
	    }
	    
	    public static int getLength(String text) {  
		    int length = 0;  
		    for (int i = 0; i < text.length(); i++) {  
		        if (new String(text.charAt(i) + "").getBytes().length > 1) {  
		            length += 2;  
		        } else {  
		            length += 1;  
		        }  
		    }  
		    return length / 2;  
		}  
}
